﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.DomainServices.Client;


namespace Candy.Web.Model
{
    /// <summary>
    /// Utility for enabling Authentication using the ClientHttp networking stack.
    /// </summary>
    public static class AuthenticationHelper
    {
        private static readonly SharedCookieHttpBehavior SharedCookieBehavior =
            new SharedCookieHttpBehavior();

        public static void ShareCookieContainer(DomainContext context)
        {
            PropertyInfo channelFactoryProperty =
                context.DomainClient.GetType().GetProperty("ChannelFactory");
            if (channelFactoryProperty == null)
            {
                throw new InvalidOperationException(
                    "There is no 'ChannelFactory' property on the DomainClient.");
            }
            ChannelFactory factory = (ChannelFactory)
                channelFactoryProperty.GetValue(context.DomainClient, null);
            ((CustomBinding)factory.Endpoint.Binding).Elements.Insert(
                0, new HttpCookieContainerBindingElement());
            factory.Endpoint.Behaviors.Add(
                AuthenticationHelper.SharedCookieBehavior);
        }

        private class SharedCookieHttpBehavior : WebHttpBehavior
        {
            private readonly SharedCookieMessageInspector _inspector =
                new SharedCookieMessageInspector();

            public override void ApplyClientBehavior(
                ServiceEndpoint endpoint,
                ClientRuntime clientRuntime)
            {
                clientRuntime.MessageInspectors.Add(this._inspector);
            }
        }

        private class SharedCookieMessageInspector : IClientMessageInspector
        {
            private readonly CookieContainer _cookieContainer =
                new CookieContainer();

            public void AfterReceiveReply(ref Message reply, object correlationState)
            {
                // do nothing
            }

            public object BeforeSendRequest(ref Message request, IClientChannel channel)
            {
                // make sure the channel uses the shared cookie container
                channel.GetProperty<IHttpCookieContainerManager>().CookieContainer =
                    this._cookieContainer;
                return null;
            }
        }
    }
}